<template>
  <div v-if="type === 'image'" >
    <div v-if="myValue !== undefined && myValue !== '' ">
      <ul class="el-upload-list el-upload-list--picture-card">
        <li tabindex="0" class="el-upload-list__item is-ready" :style="'width: ' + width + 'px;height: ' + height + 'px'">
          <div>
            <img :src="myValue" alt="" class="el-upload-list__item-thumbnail">
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-delete" @click="deleteMaterial">
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </li>
      </ul>
    </div>
    <div v-else tabindex="0" class="el-upload el-upload--picture-card"
         :style="'width: ' + width+'px;height: ' + height+'px;'+'line-height:' + height + 'px;'" @click="toSeleteMaterial">
      <i class="el-icon-plus" />
    </div>

    <el-dialog append-to-body :visible.sync="dialogVisible" width="35%">
      <img :src="url" alt="" style="width: 100%">
    </el-dialog>

    <el-dialog title="图片素材库" append-to-body :visible.sync="listDialogVisible" width="75%" height="70%">
      <el-container>
        <el-aside width="unset">
          <div style="margin-bottom: 10px">
            <el-button class="el-icon-plus" size="mini" @click="materialGroupAdd()">添加分组</el-button>
          </div>
          <el-tabs v-model="materialGroupObjId" v-loading="materialGroupLoading" tab-position="left" @tab-click="tabClick" style="height:510px;">
            <el-tab-pane v-for="(item,index) in materialGroupList" :key="item.id" :name="item.name">
              <span slot="label"> {{ item.name }}</span>
            </el-tab-pane>
          </el-tabs>
        </el-aside>
        <el-main>
          <el-card>
            <div slot="header">
              <el-row>
                <el-col :span="12">
                  <span>{{ materialGroupObj.name }}</span>
                  <span v-if="materialGroupObj.id !== '-1'">
                    <el-button size="mini" type="text" class="el-icon-edit" style="margin-left: 10px;" @click="materialGroupEdit(materialGroupObj)">重命名</el-button>
                    <el-button size="mini" type="text" class="el-icon-delete" style="margin-left: 10px;color: red" @click="materialGroupDelete(materialGroupObj)">删除</el-button>
                  </span>
                </el-col>
                <el-col :span="12" style="text-align: right;">
                  <el-upload
                    :action="uploadApi"
                    :headers="headers"
                    :file-list="[]"
                    :on-progress="handleProgress"
                    :before-upload="beforeUpload"
                    :on-success="handleSuccess"
                    :data="{type: 1}"
                    multiple>
                    <el-button size="mini" type="primary">批量上传</el-button>
                  </el-upload>
                </el-col>
              </el-row>
            </div>
            <div v-loading="tableLoading">
              <el-alert v-if="tableData.length <= 0" title="暂无数据" type="info" :closable="false" center show-icon/>
              <el-row :gutter="5">
                <el-checkbox-group v-model="urls" :max="1" @change="handleCheckedChange">
                  <el-col v-for="(item,index) in tableData" :key="index" :span="4">
                    <el-card :body-style="{ padding: '5px' }">
                      <el-tag type="">{{item.fileType}}</el-tag>
                      <video v-if="item.fileType === 'MP4'" ref="videoPlay" :src="item.imgUrl" style="width: 100%;height: 100px;background-color: black;" :z-index="999">
                        您的浏览器不支持视频播放
                      </video>
                      <el-image v-else style="width: 100%;height: 100px" :src="item.imgUrl" fit="contain" :preview-src-list="[item.imgUrl]" :z-index="999"/>
                      <div>
                        <el-checkbox class="material-name" :label="item">选择</el-checkbox>
                        <el-row>
                          <el-col :span="24" class="col-do">
                            <el-button type="text" size="medium" @click="materialDel(item)">删除</el-button>
                          </el-col>
                        </el-row>
                      </div>
                    </el-card>
                  </el-col>
                </el-checkbox-group>
              </el-row>
              <el-pagination style="margin-top: 20px;"
                :current-page.sync="page.pageNum"
                :page-sizes="[12, 24]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                class="pagination"
                @size-change="sizeChange"
                @current-change="pageChange"/>
            </div>
          </el-card>
        </el-main>
      </el-container>
      <span slot="footer" class="dialog-footer">
        <el-button @click="listDialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="sureUrls">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import { listNoPage, addObj as materialGroupAdd, delObj as materialGroupDel, putObj as materialGroupEdit }
                  from '@/api/tool/materialgroup'
import { getPage, addObj, delObj, putObj } from '@/api/tool/material'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'

export default {
  name: 'MaterialList',
  props: {
    // 素材数据
    value: {
      type: String
    },
    // 素材类型
    type: {
      type: String
    },
    uploadType: {
      type: Number,
      default() {
        return 0
      }
    },
    // 素材限制数量，默认5个
    num: {
      type: Number,
      default() {
        return 5
      }
    },
    // 宽度
    width: {
      type: Number,
      default() {
        return 150
      }
    },
    // 宽度
    height: {
      type: Number,
      default() {
        return 150
      }
    }
  },
  data() {
    return {
      headers: {
        Authorization: getToken()
      },
      dialogVisible: false,
      myValue: this.value,
      myValueCount:0,
      url: '',
      listDialogVisible: false,
      materialGroupList: [],
      materialGroupObjId: '-1',
      materialGroupObj: {},
      materialGroupLoading: false,
      tableData: [],
      resultNumber: 0,
      uploadApi:process.env.VUE_APP_BASE_API + "/common/upload/" + this.uploadType,
      page: {
        total: 0, // 总页数
        pageNum: 1, // 当前页数
        pageSize: 12, // 每页显示多少条
        // ascs: [], // 升序字段
        // descs: 'create_time'// 降序字段
      },
      tableLoading: false,
      groupId: null,
      urls: [],
      pickItem:[]
    }
  },
  computed: {
    // ...mapGetters([
    //   'uploadApi'
    // ])
  },
  created() {
    console.log('myValue',this.myValue)
  },
  watch: {
    value(val) {
      console.log('watch value', val);
      this.myValue = val;
      if (this.myValue !== undefined) {
        // if(Array.isArray( this.myValue)){
        //   this.myValueCount = this.myValue.length;
        // }else{
        // }
        // this.myValueCount = 1;
      }
    }
  },
  methods: {
    moveMaterial(index, type) {
      if (type === 'up') {
        const tempOption = this.value[index - 1];
        this.$set(this.value, index - 1, this.value[index]);
        this.$set(this.value, index, tempOption)
      }
      if (type === 'down') {
        const tempOption = this.value[index + 1];
        this.$set(this.value, index + 1, this.value[index]);
        this.$set(this.value, index, tempOption)
      }
    },
    deleteMaterial() {
      const that = this;
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        that.myValue = '';
        that.myValueCount = 0;
        that.urls = [];
        that.$emit('deleteMaterial','');
      })
    },
    toSeleteMaterial() {
      this.listDialogVisible = true;
      if (this.tableData.length <= 0) {
        this.materialGroupPage()
      }
    },
    materialGroupPage() {
      this.materialGroupLoading = true;
      listNoPage().then(response => {
        console.log('materialGroupPage ',response);
        this.materialGroupLoading = false;
        const materialGroupList = response.data;
        materialGroupList.unshift({
          id: '-1',
          name: '全部分组'
        });
        this.materialGroupList = materialGroupList;
        this.tabClick({
          index: 0
        })
      })
    },
    materialGroupDelete(materialGroupObj) {
      const that = this;
      this.$confirm('是否确认删除该分组？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        materialGroupDel(materialGroupObj.id)
          .then(function() {
            that.$delete(that.materialGroupList, materialGroupObj.index)
          })
      })
    },
    materialGroupEdit(materialGroupObj) {
      const that = this;
      this.$prompt('请输入分组名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: materialGroupObj.name
      }).then(({ value }) => {
        materialGroupEdit({
          id: materialGroupObj.id,
          name: value
        }).then(function() {
          materialGroupObj.name = value;
          that.$set(that.materialGroupList, materialGroupObj.index, materialGroupObj)
        })
      }).catch(() => {

      })
    },
    materialGroupAdd() {
      const that = this;
      this.$prompt('请输入分组名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        materialGroupAdd({
          name: value
        }).then(function() {
          that.materialGroupPage()
        })
      }).catch(() => {

      })
    },
    tabClick(tab, event) {
      this.urls = [];
      const index = Number(tab.index);
      const materialGroupObj = this.materialGroupList[index];
      materialGroupObj.index = index;
      this.materialGroupObj = materialGroupObj;
      this.materialGroupObjId = materialGroupObj.id+"";
      this.page.pageNum = 1;
      this.page.total = 0;
      if (materialGroupObj.id !== '-1') {
        this.groupId = materialGroupObj.id
      } else {
        this.groupId = null
      }
      this.getPage(this.page)
    },
    getPage(page, params) {
      this.tableLoading = true;
      getPage({
        groupId: this.groupId,
        pageNum: page.pageNum, // 当前页数
        pageSize: page.pageSize, // 每页显示多少条
      }).then(response => {
        const tableData = response.rows;
        this.page.total = response.total;
        this.page.pageNum = page.pageNum;
        this.page.pageSize = page.pageSize;
        this.tableData = tableData;
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    sizeChange(val) {
      console.log(val);
      this.page.pageNum = 1;
      this.page.pageSize = val;
      this.getPage(this.page)
    },
    pageChange(val) {
      console.log(val);
      this.page.pageNum = val;
      // this.page.pageSize = val
      this.getPage(this.page)
    },
    materialRename(item) {
      const that = this;
      this.$prompt('请输入素材名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.name
      }).then(({ value }) => {
        putObj({
          id: item.id,
          name: value
        }).then(function() {
          that.getPage(that.page)
        })
      }).catch(() => {

      })
    },
    materialUrl(item) {
      const that = this;
      this.$prompt('素材链接', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.url
      }).then(({ value }) => {

      }).catch(() => {

      })
    },
    materialDel(item) {
      const that = this;
      this.$confirm('是否确认删除该素材？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        delObj(item.id)
          .then(function() {
            that.getPage(that.page)
          })
      })
    },
    handleCommand(command) {
      const that = this;
      const s = command.split('-');
      putObj({
        id: s[0],
        groupId: s[1]
      }).then(function() {
        that.getPage(that.page)
      })
    },
    handleProgress(event, file, fileList) {
      console.log('handleProgress',event)
      // let uploadProgress = file.percentage.toFixed(0)
      // this.uploadProgress = uploadProgress
    },
    handleSuccess(response, file, fileList) {
      console.log('handleSuccess response',response);
      console.log('handleSuccess file',file);
      console.log('handleSuccess fileList',fileList);
      const that = this;
      this.uploadProgress = 0;
      addObj({
        type: '1',
        groupId: this.groupId !== '-1' ? this.groupId : null,
        name: file.name,
        url: response.data.fileName
      }).then(() => {
        this.resultNumber++;
        if (fileList.length === this.resultNumber) {
          that.getPage(that.page);
          this.resultNumber = 0
        }
      })
    },
    beforeUpload(file) {
      const isPic =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'video/mp4' ||
        file.type === 'image/jpg';
      const isLt2M = file.size / 1024 / 1024 < 30;
      if (!isPic) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG、GIF 格式, 视频只能是  MP4格式!');
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPic && isLt2M
    },
    handleCheckedChange(value){
      console.log('handleCheckedChange',value);
      this.pickItem = value;
    },
    /**
     *  确认选中图片
     */
    sureUrls() {
      console.log('this.urls:', this.urls);
      this.myValue = this.urls[0].imgUrl;
      console.log('sureUrls pickItem',this.pickItem);
      this.$emit('handleChecked', this.pickItem);
      this.listDialogVisible = false;
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-icon-circle-close{
    color: red;
  }
  .material-name{
    padding: 8px 0px;
  }
  .col-do{
    text-align: center;
  }
  .button-do{
    padding: unset!important;
    font-size: 12px;
  }
</style>

